package models

import (
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// User 用户模型
type User struct {
	gorm.Model
	// 用户名，唯一
	Username string `gorm:"unique;not null;size:50" `
	// 密码，加密存储
	Password string `gorm:"not null;size:100" `
	// 头像 URL
	Avatar string `gorm:"size:255" `
	// 手机号
	Phone string `gorm:"size:20;uniqueIndex:idx_phone_email_id" `
	// 邮箱，唯一
	Email string `gorm:"size:100;uniqueIndex:idx_phone_email_id" `
	// 地址
	Address string `gorm:"size:255" `
	// 性别
	Sex string `gorm:"size:10" `
	// 生日
	Birthday string
	// 会员余额
	Balance string `gorm:"default:0" `
}

const (
	PasswordEncryptionDifficulty int = 12 // 密码加密难度
)

// SetPassword 密码加密
func (user *User) SetPassword(pwd string) error {
	bytes, err := bcrypt.GenerateFromPassword([]byte(pwd), PasswordEncryptionDifficulty)
	if err != nil {
		return err
	}
	user.Password = string(bytes)
	return nil
}

// CheckPassword 密码解密
func (user *User) CheckPassword(pwd string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(pwd))
	return err == nil
}
